package com.lby.graduation.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lby.graduation.entity.User;
import com.lby.graduation.service.UserService;
import com.lby.graduation.util.JwtUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/doLogin")
public class doLoginController {
    @Resource
    private UserService userService;

    /*登录成功后生成token*/
    @GetMapping("/createToken")
    public Map<String, Object> createToken(String username, String password) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username).eq("password", password));
        HashMap<String, Object> map = new HashMap<>();
        if (user.getUsername() == null) {
            map.put("error", "用户不存在");
            map.put("state", "false");
            return map;
        }
        HashMap<String, String> payload = new HashMap<>();//封装用户信息到payload
        payload.put("username", user.getUsername());
        payload.put("role", user.getRole());
        payload.put("userId", String.valueOf(user.getUserId()));
        String token = JwtUtils.getToken(payload);//生成token
       /*封装返回前端的信息*/
        map.put("state", true);
        map.put("token", token);
        map.put("userId", user.getUserId());
        map.put("username", user.getUsername());
        map.put("role",user.getRole());
        map.put("userImage",user.getImage());
        map.put("msg", "登录成功");
        return map;
    }

    /*解析token*/
    @GetMapping("/decodeJwt")
    public Map<String, Object> verifyToken(HttpServletRequest request) {

        String token = request.getHeader("token");
        DecodedJWT verify = JwtUtils.verify(token);
        String username = verify.getClaim("username").asString();
        //业务逻辑
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("username", username);
        map.put("msg", "请求成功");
        return map;
    }


}
